<?php
/**
 * link: http://bbs.52jscn.com
 * copyright: Copyright (c) 2018 人人禾匠商城
 * author: jack_guo
 */

namespace app\forms\mall\export;

use app\core\CsvExport;

class SendStatisticsExport extends BaseExport
{

    public $type;

    public function fieldsList()
    {
        return [
            [
                'key' => 'date',
                'value' => '日期',
            ],
            [
                'key' => 'name',
                'value' => '名称',
            ],
            [
                'key' => 'all_num',
                'value' => '发放总数',
            ],
            [
                'key' => 'use_num',
                'value' => '已使用数量',
            ],
            [
                'key' => 'unuse_num',
                'value' => '未使用数量',
            ],
            [
                'key' => 'end_num',
                'value' => '已失效数量',
            ],
        ];
    }

    public function export($query)
    {
        $list = $query->groupBy('`date`,name')
            ->asArray()
            ->all();
        $this->transform($list);
        $this->getFields();
        $dataList = $this->getDataList();
        if ($this->type == 'card') {
            $name = '卡券-';
        } else {
            $name = '优惠券-';
        }

        $fileName = $name . '发放统计' . date('YmdHis');
        (new CsvExport())->export($dataList, $this->fieldsNameList, $fileName);
    }

    protected function transform($list)
    {
        $newList = [];
        $arr = [];

        $number = 1;
        foreach ($list as $key => $item) {
            $arr['number'] = $number++;
            $item['all_num'] = intval($item['all_num']);
            $item['use_num'] = intval($item['use_num']);
            $item['unuse_num'] = intval($item['unuse_num']);
            $item['end_num'] = intval($item['end_num']);

            $arr = array_merge($arr, $item);


            $newList[] = $arr;
        }
        $this->dataList = $newList;
    }

    protected function getFields()
    {
        $arr = [];
        foreach ($this->fieldsList() as $key => $item) {
            $arr[$key] = $item['key'];
        }
        $this->fieldsKeyList = $arr;
        parent::getFields(); // TODO: Change the autogenerated stub
    }
}
